using System.Globalization;
using System.Windows.Data;
using DimensionsHelper.Client.Helpers;

namespace DimensionsHelper.Client.Converters;


public class EnumStringConverter : IValueConverter
{
    
    public static EnumStringConverter Instance { get; } = new();
    
    
    public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        return value?.GetType().IsEnum == true ? ConvertEnumToString(value) : ConvertStringToEnum(value, targetType);
    }
    
    public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        return value?.GetType().IsEnum == true ? ConvertEnumToString(value) : ConvertStringToEnum(value, targetType);
    }


    private static string ConvertEnumToString(object? value)
    {
        return EnumStringCache.TryGetDescriptionFromEnum(value, out string? description)
            ? description
            : $"Cannot convert {value} to string.";
    }


    private static object ConvertStringToEnum(object? value, Type targetType)
    {
        if (value is not string description)
        {
            return "";
        }
        
        return Enum.TryParse(targetType, description, true, out object? result)
            ? result
            : EnumStringCache.GetEnumFromDescription(targetType, description);
    }
    
}